//
//  BADUnSuccessViewController.m
//  BAD
//
//  Created by Can on 2018/5/15.
//  Copyright © 2018年 hwd. All rights reserved.
//

#import "BADUnSuccessViewController.h"
#import "BADSuccessViewController.h"
#import "BADLinkViewController.h"
#import "MBProgressHUD.h"
#import "BADGetIphone.h"

@interface BADUnSuccessViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,CLLocationManagerDelegate>{
    CLLocationManager *locationmanager;//定位服务
    NSString *strlatitude;//经度
    NSString *strlongitude;//纬度
    CGFloat height;
}

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIImagePickerController *imagePicker;

@property (nonatomic, strong) UIImage *imgPicker;

@property (nonatomic, strong) UIButton *cameraBtn;

@end

@implementation BADUnSuccessViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    
    height = StatusBarHeight;
    
    [self getLocation];
    
    [self creatTableView];
    
    [self creatView];
}

- (void)creatTableView
{
    UIImageView *imageView = [UIViewControls creatImageView:CGRectMake(0, -height, SCREENW, SCREENH + height) imageName:@"bg"];
    [self.view addSubview:imageView];
    imageView.userInteractionEnabled = YES;
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH + height) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
}

- (void)creatView
{
    UIView *headView = [UIView new];
    headView.backgroundColor = [UIColor clearColor];

    UIImageView *bioisland = [UIViewControls creatImageView:CGRectMake((SCREENW - 292/2*screenW_6)/2, 161/2*screenW_6, 292/2*screenW_6, 105/2*screenW_6) imageName:@"logo3"];
    [headView addSubview:bioisland];
    
    UIImageView *backImageView = [UIViewControls creatImageView:CGRectMake(SCREENW - 25*screenW_6 - 35*screenW_6, 105/2*screenW_6, 35*screenW_6, 35*screenW_6) imageName:@"close2"];
    [headView addSubview:backImageView];
    backImageView.userInteractionEnabled = YES;
    //添加点击手势（即点击图片后退出全屏）
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bkView)];
    [backImageView addGestureRecognizer:tapGesture];
    
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(15*screenW_6, CGRectGetMaxY(bioisland.frame) + 128/2*screenW_6, SCREENW - 30*screenW_6, 300)];
    backView.backgroundColor = [UIColor whiteColor];
    backView.layer.cornerRadius = 8;
    backView.layer.masksToBounds = YES;
    [self creatBackView:backView rect:backView.frame];

    headView.frame = CGRectMake(0, 0, SCREENW, CGRectGetMaxY(backView.frame) + 45*screenW_6);
    
    [headView addSubview:backView];
    
    [_tableView setTableHeaderView:headView];
}

- (UIView *)creatBackView:(UIView *)backView rect:(CGRect)rect
{
    UIImageView *successImg = [UIViewControls creatImageView:CGRectMake((backView.width - 103/2*screenW_6)/2, 47/2*screenW_6, 103/2*screenW_6, 103/2*screenW_6) imageName:@"icon05"];
    [backView addSubview:successImg];
    
    UILabel *successLable = [UIViewControls creatLable:CGRectMake(0, CGRectGetMaxY(successImg.frame) + 20*screenW_6, backView.width, 16*screenW_6) text:@"Verification unsuccessful" textColor:[UIColor colorWithHexString:@"#3088fb"] textFont:[UIFont systemFontOfSize:15.28*screenW_6]];
    [backView addSubview:successLable];
    
    UILabel *this = [UIViewControls creatLable:CGRectMake(10*screenW_6, CGRectGetMaxY(successLable.frame) + 15*screenW_6, backView.width - 20*screenW_6, 14*screenW_6) text:@"This verification was unsuccessful. Please confirm if the following problems exist:" textColor:[UIColor colorWithHexString:@"#bbb9b9"] textFont:[UIFont systemFontOfSize:13.22*screenW_6]];
    this.frame = CGRectMake(10*screenW_6, CGRectGetMaxY(successLable.frame) + 15*screenW_6, backView.width - 20*screenW_6, [UIViewControls lableHeight:this]);
    [backView addSubview:this];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(10*screenW_6, CGRectGetMaxY(this.frame) + 47/2*screenW_6, backView.width - 20*screenW_6, 1)];
    line.backgroundColor = [UIColor colorWithHexString:@"#bbb9b9"];
    [backView addSubview:line];
    
    UILabel *Did = [self creatLable:CGRectMake(10*screenW_6, CGRectGetMaxY(line.frame) + 16*screenW_6, backView.width - 20*screenW_6, 25/2*screenW_6) text:@"1.Did you photograph the right area shown below?" font:[UIFont systemFontOfSize:25/2*screenW_6]];
    [backView addSubview:Did];
    
    NSArray *didImages = @[@"tu01",@"tu02",@"tu03"];
    for (int i = 0; i<3; i++) {
        UIButton *button = [UIViewControls creatButtonSetImage:CGRectMake(backView.width/3*i, CGRectGetMaxY(Did.frame) + 16*screenW_6, backView.width/3, 174/2*screenW_6) imageName:didImages[i]];
        [backView addSubview:button];
    }
    
    UIView *lineTwo = [[UIView alloc]initWithFrame:CGRectMake(10*screenW_6, CGRectGetMaxY(Did.frame) + 174/2*screenW_6 + 32*screenW_6, backView.width - 20*screenW_6, 1)];
    lineTwo.backgroundColor = [UIColor colorWithHexString:@"#bbb9b9"];
    [backView addSubview:lineTwo];
    
    UILabel *Do = [self creatLable:CGRectMake(10*screenW_6, CGRectGetMaxY(lineTwo.frame) + 19*screenW_6, backView.width - 20*screenW_6, 25/2*screenW_6) text:@"2.Do you have these issues with your photo?" font:[UIFont systemFontOfSize:25/2*screenW_6]];
    [backView addSubview:Do];
    
    NSArray *doTitle = @[@"Shadow",@"Incomplete",@"Light spot",@"Blurry"];
    NSArray *doImages = @[@"tu04",@"tu05",@"tu06",@"tu07"];
    for (int i = 0; i<4; i++) {
        UILabel *lable = [UIViewControls creatLable:CGRectMake(backView.width/4*i, CGRectGetMaxY(Do.frame) + 31/2*screenW_6, backView.width/4, 10*screenW_6) text:doTitle[i] textColor:[UIColor colorWithHexString:@"#595757"] textFont:[UIFont systemFontOfSize:10*screenW_6]];
        [backView addSubview:lable];
        
        UIButton *button = [UIViewControls creatButtonSetImage:CGRectMake(backView.width/4*i, CGRectGetMaxY(lable.frame) + 13*screenW_6, backView.width/4, 144/2*screenW_6) imageName:doImages[i]];
        [backView addSubview:button];
    }
    
    UIView *lineThree = [[UIView alloc]initWithFrame:CGRectMake(10*screenW_6, CGRectGetMaxY(Do.frame) + 144/2*screenW_6 + 31/2*screenW_6 + 10*screenW_6 + 13*screenW_6 + 29/2*screenW_6, backView.width - 20*screenW_6, 1)];
    lineThree.backgroundColor = [UIColor colorWithHexString:@"#bbb9b9"];
    [backView addSubview:lineThree];
    
    UILabel *ifLable = [self creatLable:CGRectMake(10*screenW_6, CGRectGetMaxY(lineThree.frame) + 17*screenW_6, backView.width - 20*screenW_6, 15/2*screenW_6) text:@"* if any of the abovementioned issue appears on your photo, please click 'Retake photo' button." font:[UIFont systemFontOfSize:15/2*screenW_6]];
    ifLable.frame = CGRectMake(10*screenW_6, CGRectGetMaxY(lineThree.frame) + 17*screenW_6, backView.width - 20*screenW_6, [UIViewControls lableHeight:ifLable]);
    [backView addSubview:ifLable];
    
    UILabel *ifUsLable = [self creatLable:CGRectMake(10*screenW_6, CGRectGetMaxY(ifLable.frame) + 5*screenW_6, backView.width - 20*screenW_6, 15/2*screenW_6) text:@"* ifthe product still cannot be recognised after multiple correct attempts, please click 'Contact Us' button." font:[UIFont systemFontOfSize:15/2*screenW_6]];
    ifUsLable.frame = CGRectMake(10*screenW_6, CGRectGetMaxY(ifLable.frame) + 5*screenW_6, backView.width - 20*screenW_6, [UIViewControls lableHeight:ifUsLable]);
    [backView addSubview:ifUsLable];
    
    UIButton *retake = [UIViewControls creatButtonBackImage:CGRectMake((backView.width/2 - 121*screenW_6)/2, CGRectGetMaxY(ifUsLable.frame) + 65/2*screenW_6, 121*screenW_6, 93/2*screenW_6) imageName:@"button02"];
    [retake addTarget:self action:@selector(pickCamera:) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:retake];
    
    UIButton *contact = [UIViewControls creatButtonBackImage:CGRectMake((backView.width/2 - 121*screenW_6)/2 + backView.width/2, CGRectGetMaxY(ifUsLable.frame) + 65/2*screenW_6, 121*screenW_6, 93/2*screenW_6) imageName:@"button03"];
    [contact addTarget:self action:@selector(contactUs:) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:contact];
    
    backView.frame = CGRectMake(rect.origin.x, rect.origin.y, SCREENW - 30*screenW_6, CGRectGetMaxY(contact.frame) + 30*screenW_6);
    
    return backView;
}

- (void)pickCamera:(UIButton *)btn
{
    [self creatPicker];
}

- (void)creatPicker
{
    _imagePicker = [[UIImagePickerController alloc] init];
    _imagePicker.delegate = self;
    _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) return;
    [self presentViewController:_imagePicker animated:YES completion:nil];
    
    CGSize screenBounds = [UIScreen mainScreen].bounds.size;
    CGFloat cameraAspectRatio = 4.0f/3.0f;
    CGFloat camViewHeight = screenBounds.width * cameraAspectRatio;
    CGFloat scale = screenBounds.height / camViewHeight;
    _imagePicker.cameraViewTransform = CGAffineTransformMakeTranslation(0, (screenBounds.height - camViewHeight) / 2.0);
    _imagePicker.cameraViewTransform = CGAffineTransformScale(_imagePicker.cameraViewTransform, scale, scale);
    _imagePicker.showsCameraControls  = NO;
    
    UIView *toolView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREENH - 100*screenW_6, SCREENW, 100*screenW_6)];
    toolView.backgroundColor = [UIColor blackColor];
    toolView.alpha = 0.5;
    
    UIButton *cancel = [UIViewControls creatButtonSetImage:CGRectMake(20*screenW_6, 25*screenW_6, 50*screenW_6, 50*screenW_6) imageName:@"arrow_down2"];
    [cancel addTarget:self action:@selector(cancelCamera) forControlEvents:UIControlEventTouchUpInside];
    [toolView addSubview:cancel];

    _cameraBtn = [UIViewControls creatButtonSetImage:CGRectMake((SCREENW - 132/2*screenW_6)/2, (100*screenW_6 -132/2*screenW_6)/2, 132/2*screenW_6, 132/2*screenW_6) imageName:@"Camera_button"];
    [_cameraBtn addTarget:self action:@selector(savePhoto) forControlEvents:UIControlEventTouchUpInside];
    [toolView addSubview:_cameraBtn];
    //把自定义的view设置到imagepickercontroller的overlay属性中
    _imagePicker.cameraOverlayView = toolView;
}

-(void)cancelCamera{
    [_imagePicker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

-(void)savePhoto{
    _cameraBtn.userInteractionEnabled = NO;

    [_imagePicker takePicture];
}

- (void)contactUs:(UIButton *)btn
{
    BADLinkViewController *linkVC = [BADLinkViewController new];
    linkVC.strUrl = @"http://www.bioisland.com.au/contact-us/";
    [self.navigationController pushViewController:linkVC animated:YES];
}

- (void)bkView
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"])
    {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        [self creatBigImgView:image];
        
        _imgPicker = [self imageCompressWithSimple:image];
        
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
}

- (void)creatBigImgView:(UIImage *)image
{
    //初始化要显示的图片内容的imageView
    UIImageView *browseImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -height, SCREENW, SCREENH + height)];
    [browseImgView setBackgroundColor:[UIColor blackColor]];

    [browseImgView setContentMode:UIViewContentModeScaleAspectFill];
    browseImgView.clipsToBounds = YES;
    //要显示的图片，即要放大的图片
    browseImgView.image = image;
    browseImgView.tag = 1001;
    UIApplication *ap = [UIApplication sharedApplication];
    [ap.keyWindow addSubview:browseImgView];
    
    browseImgView.userInteractionEnabled = YES;
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, browseImgView.height - 100*screenW_6, SCREENW, 100*screenW_6)];
    [view setBackgroundColor:[UIColor blackColor]];
    view.alpha = 0.5;
    [browseImgView addSubview:view];
    
    UIButton *cancel = [UIViewControls creatButton:CGRectMake(20*screenW_6, 25*screenW_6, 80*screenW_6, 50*screenW_6) title:@"Retry"];
    [cancel addTarget:self action:@selector(cancelImage) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:cancel];
    
    UIButton *OK = [UIViewControls creatButton:CGRectMake(SCREENW - 50*screenW_6 - 20*screenW_6, (100*screenW_6 - 50*screenW_6)/2, 50*screenW_6, 50*screenW_6) title:@"OK"];
    [OK addTarget:self action:@selector(okImg) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:OK];
}

- (void)cancelImage
{
    _cameraBtn.userInteractionEnabled = YES;
    
    [self closeView];
    
    [self creatPicker];
}

- (void)okImg
{
    _cameraBtn.userInteractionEnabled = YES;
    
    [self creatAlphaView];
    
    [self closeView];
    
    [self monitorNetworking];
}

-(void)closeView{
    
    [[[UIApplication sharedApplication].keyWindow viewWithTag:1001] removeFromSuperview];
}

- (void)creatAlphaView
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, -44, SCREENW, SCREENH + 88)];
    [view setBackgroundColor:[UIColor blackColor]];
    view.tag = 1006;
    view.alpha = 0.5;
    UIApplication *ap = [UIApplication sharedApplication];
    [ap.keyWindow addSubview:view];
    
    CGFloat width = [GetStrWidthAndHeight getStringWidthWith:@"Please Waiting..." andHeigth:15*screenW_6 andFont:[UIFont systemFontOfSize:15*screenW_6]];
    
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 150 + width, 75)];
    [backView setBackgroundColor:[UIColor whiteColor]];
    backView.tag = 1011;
    backView.layer.cornerRadius = 8;
    backView.layer.masksToBounds = YES;
    [ap.keyWindow addSubview:backView];
    backView.center = CGPointMake(ap.keyWindow.centerX, ap.keyWindow.centerY);
    
    UIView *hudView = [[UIView alloc]initWithFrame:CGRectMake(25, 0, 75, 75)];
    [hudView setBackgroundColor:[UIColor whiteColor]];
    [backView addSubview:hudView];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:hudView animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.color = [UIColor whiteColor];
    //11，背景框的最小大小
    hud.minSize = CGSizeMake(25, 25);
    //13,是否强制背景框宽高相等
    hud.square = YES;
    
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(100, 25/2, width, 50)];
    lable.text = @"Please Waiting...";
    lable.textColor = [UIColor blackColor];
    lable.font = [UIFont systemFontOfSize:15*screenW_6];
    lable.textAlignment = NSTextAlignmentRight;
    [backView addSubview:lable];
}

#pragma mark - ------------- 监测网络状态 -------------
- (void)monitorNetworking
{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case -1:
                NSLog(@"未知网络");
                break;
            case 0:
                NSLog(@"网络不可达");
                break;
            case 1:
            {
                NSLog(@"GPRS");
            }
                break;
            case 2:
            {
                NSLog(@"wifi");
            }
                break;
            default:
                break;
        }
        if (status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi) {
            
            [self postImage:self->_imgPicker];
            
        }else{
            [HudHelper hideHudToView:self.view];
            [HudHelper showAlertViewWithMessage:@"Please check the network"];
        }
    }];
}

- (UIImage*)imageCompressWithSimple:(UIImage*)image{
    CGFloat scaledWidth = 1700;
    CGFloat scaledHeight = 1700/image.size.width * image.size.height;
    
    if (image.size.width > image.size.height) {
        scaledWidth = 1700/image.size.height * image.size.width;
        scaledHeight = 1700;
    }
    CGSize secSize =CGSizeMake(scaledWidth, scaledHeight);
    //TODO:设置新图片的宽高
    UIGraphicsBeginImageContext(secSize); // this will crop
    [image drawInRect:CGRectMake(0,0,scaledWidth,scaledHeight)];
    UIImage* newImage= UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (void)postImage:(UIImage *)image
{
    NSMutableDictionary *dic = [NSMutableDictionary new];
    NSData *imageData = UIImageJPEGRepresentation(image,0.85);
    [dic setValue:@"bioisland" forKey:@"app_name"];
    [dic setValue:[BADGetIphone getIP] forKey:@"ip"];
    [dic setValue:@"iOS" forKey:@"dev_os"];
    [dic setValue:[[UIDevice currentDevice] systemVersion] forKey:@"dev_os_ver"];
    [dic setValue:[BADGetIphone getDeviceVersion] forKey:@"dev_model"];
    [dic setValue:strlatitude forKey:@"latitude"];
    [dic setValue:strlongitude forKey:@"longitude"];
    //    [dic setValue:@"10" forKey:@"userid"];
    //    [dic setValue:@"name" forKey:@"nickname"];
    //    [dic setValue:@"1" forKey:@"sex"];
    //    [dic setValue:@"url" forKey:@"headimgurl"];
    
    [HttpRequest PostFileRequestUrl:imageData Dic:dic completion:^(NSDictionary *responseDic) {
//        NSLog(@"responseDic:%@",responseDic);
        [[[UIApplication sharedApplication].keyWindow viewWithTag:1006] removeFromSuperview];
        [[[UIApplication sharedApplication].keyWindow viewWithTag:1011] removeFromSuperview];

        if ([[responseDic objectForKey:@"errcode"] boolValue]) {
            
        }else{
            NSString *ID = [[responseDic objectForKey:@"result"] objectForKey:@"prod_id"];
            
            if ([ID intValue] >= 3 && [ID intValue] <= 13) {
                BADSuccessViewController *successVC = [BADSuccessViewController new];
                successVC.ID = ID;
                [self.navigationController pushViewController:successVC animated:YES];
            }
        }
    }];
}

- (UILabel *)creatLable:(CGRect)rect text:(NSString *)text font:(UIFont *)font
{
    UILabel *lable = [[UILabel alloc]initWithFrame:rect];
    lable.text = text;
    lable.textColor = [UIColor colorWithHexString:@"#000000"];
    lable.font = font;
    lable.textAlignment = NSTextAlignmentLeft;
    return lable;
}

-(NSString *)deviceWANIPAddress
{
    NSURL *ipURL = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"];
    NSData *data = [NSData dataWithContentsOfURL:ipURL];
    NSDictionary *ipDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
    NSString *ipStr = nil;
    if (ipDic && [ipDic[@"code"] integerValue] == 0) { //获取成功
        ipStr = ipDic[@"data"][@"ip"];
    }
    return (ipStr ? ipStr : @"");
}


-(void)getLocation
{
    //判断定位功能是否打开
    if ([CLLocationManager locationServicesEnabled]) {
        locationmanager = [[CLLocationManager alloc]init];
        locationmanager.delegate = self;
        [locationmanager requestAlwaysAuthorization];
        [locationmanager requestWhenInUseAuthorization];
        //设置寻址精度
        locationmanager.desiredAccuracy = kCLLocationAccuracyBest;
        locationmanager.distanceFilter = 5.0;
        [locationmanager startUpdatingLocation];
    }
}

#pragma mark CoreLocation delegate (定位失败)
//定位失败后调用此代理方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Turn on [Location Services] to allow [BAD] to get your position" message:@"Please turn on the location service in the system settings (Settings> Privacy> Location Services> On)" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Setting" , nil];
    alertView.delegate = self;
    alertView.tag = 1;
    [alertView show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1) {
        if (buttonIndex == 1) {
            //跳转到定位权限页面
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if( [[UIApplication sharedApplication]canOpenURL:url] ) {
                [[UIApplication sharedApplication] openURL:url];
            }
        }
    }
}
#pragma mark 定位成功后则执行此代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    [locationmanager stopUpdatingHeading];
    //旧址
    CLLocation *currentLocation = [locations lastObject];
    
    //打印当前的经度与纬度
    strlatitude = [NSString stringWithFormat:@"%f",currentLocation.coordinate.latitude];
    strlongitude = [NSString stringWithFormat:@"%f",currentLocation.coordinate.longitude];
    NSLog(@"lat:%@ long:%@",strlatitude,strlongitude);
}

- (UIImage *)sd_animatedGIFNamed:(NSString *)name {
    CGFloat scale = [UIScreen mainScreen].scale;
    
    if (scale > 1.0f) {
        NSString *retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"];
        
        NSData *data = [NSData dataWithContentsOfFile:retinaPath];
        
        if (data) {
            return [UIImage sd_animatedGIFWithData:data];
        }
        
        NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];
        
        data = [NSData dataWithContentsOfFile:path];
        
        if (data) {
            return [UIImage sd_animatedGIFWithData:data];
        }
        
        return [UIImage imageNamed:name];
    }
    else {
        NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];
        
        NSData *data = [NSData dataWithContentsOfFile:path];
        
        if (data) {
            return [UIImage sd_animatedGIFWithData:data];
        }
        
        return [UIImage imageNamed:name];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
